package com.itlaobing.demo.servlet;

import com.itlaobing.demo.model.OnlineVO;
import com.itlaobing.demo.model.UserinfoModel;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Classname OnlineServlet
 * @Description TODO()
 * @Date 2020/11/13 0013 10:40
 * @Author by Administrator
 * @Version v1.0
 */
@WebServlet("/online")
public class OnlineServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 请求 在线用户列表 online.jsp

        // 拿到 在线用户列表
        ServletContext context = getServletContext();
        // 在线用户
        Map<String, HttpSession> map = (Map<String, HttpSession>) context.getAttribute("onlineUsers");

        List<OnlineVO> onlineVOS = new ArrayList<>();

        for (HttpSession session : map.values()){
            OnlineVO vo = new OnlineVO();
            vo.setId(session.getId());
            UserinfoModel model = (UserinfoModel) session.getAttribute("user");
            vo.setUsername(model.getUsername());
            vo.setStartTimestamp(new Date(session.getCreationTime()));
            vo.setLastAccessTime(new Date(session.getLastAccessedTime()));
            vo.setTimeout(session.getMaxInactiveInterval() + 0L);

            onlineVOS.add(vo);
        }
        // 放到 request 中
        req.setAttribute("list", onlineVOS);

        req.getRequestDispatcher("WEB-INF/pages/sys/online.jsp").forward(req, resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
